import { Controller, Get, Post, Body, Param, Delete, Session, HttpException, HttpStatus, Req } from '@nestjs/common';
import { RobotService } from './robot.service';
import { PermissionService } from '../permission/permission.service';
import { UserRepository } from '../user/user.repository';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../user/user.entity';
import { Repository } from 'typeorm';

@Controller('robot')
export class RobotController {
  constructor(
    private readonly robotService: RobotService,
    private readonly permissionService: PermissionService,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) { }

  @Get('getRobot')
  async findAll(@Session() session: Record<string, any>, @Req() req: any) {
    console.log('调用getRobot API，用户ID:', session.userId);

    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    const robots = await this.robotService.findAll();
    console.log('获取到机器人列表:', robots);

    // 为每个机器人添加权限信息
    const permissionList = await this.permissionService.findAll();
    const userInfo = await this.userRepository.findOne({ where: { id: session.userId } });

    const robotsWithPermission = robots.map(robot => {
      const role = this.permissionService.getPermission(userInfo, permissionList, robot);
      return {
        ...robot,
        role  // 将权限角色添加到每个机器人对象
      };
    });

    console.log('返回带权限的机器人列表:', robotsWithPermission);
    return {
      code: 0,
      data: robotsWithPermission,
      msg: 'success'
    };
  }

  @Post('createRobot')
  async create(@Body() createRobotDto: any, @Session() session: Record<string, any>) {
    if (!session.userId) {
      throw new HttpException('未登录', HttpStatus.UNAUTHORIZED);
    }

    const robot = await this.robotService.create(createRobotDto);
    return {
      success: 1,
      code: 0,
      data: robot
    };
  }

  @Post('updataRobot')
  async update(@Body() updateRobotDto: any, @Session() session: Record<string, any>, @Req() req: any) {
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    const userRole = req['userRole'];
    if (userRole !== 'admin') {
      return {
        code: 1,
        data: null,
        msg: '无权操作'
      };
    }

    const { id, ...robotData } = updateRobotDto;
    const robot = await this.robotService.update(id, robotData);
    return {
      code: 0,
      data: robot,
      msg: 'success'
    };
  }

  @Post('removeRobot')
  async remove(@Body() body: { id: number }, @Session() session: Record<string, any>, @Req() req: any) {
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    const userRole = req['userRole'];
    if (userRole !== 'admin') {
      return {
        code: 1,
        data: null,
        msg: '无权操作'
      };
    }

    await this.robotService.remove(body.id);
    return {
      code: 0,
      data: null,
      msg: 'success'
    };
  }
} 